package webapi.storage.localdisk;

import org.springframework.core.io.FileSystemResource;
import webapi.storage.ReadOnlyDataChunk;

import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Path;


public class LocalDiskReadOnlyDataChunk implements Closeable, ReadOnlyDataChunk {
    private final Path filePath;
    private final FileChannel inputFileChannel;

    /**
     * @throws IOException 文件无法打开, 请检查文件存储路径权限是否允许读
     */
    public LocalDiskReadOnlyDataChunk(Path filePath) throws IOException {
        this.filePath = filePath;
        inputFileChannel = FileChannel.open(filePath);
    }

    @Override
    public org.springframework.core.io.Resource getResource() {
        return new FileSystemResource(filePath);
    }

    /**
     * @throws IOException 文件读写错误
     */
    @Override
    public long transferTo(long position, long count, WritableByteChannel target) throws IOException {
        return inputFileChannel.transferTo(position, count, target);
    }

    /**
     * @throws IOException 磁盘IO错误导致文件无法关闭
     */
    @Override
    public void close() throws IOException {
        if (null != inputFileChannel) {
            inputFileChannel.close();
        }
    }
}
